package com.agentai.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.agentai.framework.mybatis.service.impl.BaseServiceImpl;
import com.agentai.system.entity.SysRoleAreaScopeEntity;
import com.agentai.system.mapper.SysRoleAreaScopeMapper;
import com.agentai.system.service.SysRoleAreaScopeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色区域权限
 */
@Service
public class SysRoleAreaScopeServiceImpl extends BaseServiceImpl<SysRoleAreaScopeMapper, SysRoleAreaScopeEntity>
        implements SysRoleAreaScopeService {


    @Override
    @Transactional(rollbackFor = Exception.class, timeout = 30)
    public void saveOrUpdate(Long roleId, List<String> areaCodeList) {
        // 数据库区域编码列表
        List<String> dbAreaCodeList = getAreaCodeList(roleId);

        // 需要新增的区域编码
        Collection<String> insertAreaCodeList = CollUtil.subtract(areaCodeList, dbAreaCodeList);
        if (CollUtil.isNotEmpty(insertAreaCodeList)) {
            List<SysRoleAreaScopeEntity> areaList = insertAreaCodeList.stream().map(areaCode -> {
                SysRoleAreaScopeEntity entity = new SysRoleAreaScopeEntity();
                entity.setAreaCode(areaCode);
                entity.setRoleId(roleId);
                return entity;
            }).collect(Collectors.toList());

            // 批量新增
            saveBatch(areaList);
        }

        // 需要删除的区域编码
        Collection<String> deleteAreaCodeList = CollUtil.subtract(dbAreaCodeList, areaCodeList);
        if (CollUtil.isNotEmpty(deleteAreaCodeList)) {
            LambdaQueryWrapper<SysRoleAreaScopeEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysRoleAreaScopeEntity::getRoleId, roleId);
            queryWrapper.in(SysRoleAreaScopeEntity::getAreaCode, deleteAreaCodeList);

            remove(queryWrapper);
        }
    }

    @Override
    public List<String> getAreaCodeList(Long roleId) {
        return baseMapper.getAreaCodeList(roleId);
    }

    @Override
    public void deleteByRoleIdList(List<Long> roleIdList) {
        remove(new LambdaQueryWrapper<SysRoleAreaScopeEntity>().in(SysRoleAreaScopeEntity::getRoleId, roleIdList));
    }
}
